package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.entity.Employee;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.PasswordErrorException;
import com.sky.mapper.EmployeeMapper;
import com.sky.result.PageResult;
import com.sky.service.EmployeeService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;


    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        if(employee.getStatus()==StatusConstant.DISABLE){
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //密码比对
        BCryptPasswordEncoder BcryptPasswordEncoder=new BCryptPasswordEncoder();
        boolean PasswordeEstimate=BcryptPasswordEncoder.matches(password,employee.getPassword());
        if (!PasswordeEstimate) {
            //密码错误
            int errnums=employee.getErrnums();
            if(errnums+1>=5){
                employeeMapper.setUserStatus(StatusConstant.DISABLE,employee.getId());
                throw new PasswordErrorException(MessageConstant.ACCOUNT_LOCKED);
            }else{
                int seterrnums=errnums+1;
                employeeMapper.setUserErrnums(seterrnums, employee.getId());
            }

            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }
        employeeMapper.setUserStatus(StatusConstant.ENABLE,employee.getId());
        employeeMapper.setUserErrnums(0,employee.getId());


        //3、返回实体对象
        return employee;
    }

    /**
     * 添加员工
     * @param employeeDTO
     * @return
     */
    @Override
    public int AddUser(EmployeeDTO employeeDTO) {
        //创建一个和数据库相匹配的对象
        Employee employee=new Employee();

        //把数据填充进去
        BeanUtils.copyProperties(employeeDTO,employee);

        //添加默认密码
        BCryptPasswordEncoder bCryptPasswordEncoder=new BCryptPasswordEncoder();
        String password=bCryptPasswordEncoder.encode(PasswordConstant.DEFAULT_PASSWORD);//添加默认密码123456 并加密

        employee.setPassword(password);
        //添加状态值
        employee.setStatus(StatusConstant.ENABLE);

        //这里 已经 通过AOP 反射 添加公共字段
        //设置创建时间和修改时间
//        employee.setUpdateTime(LocalDateTime.now());
//        employee.setCreateTime(LocalDateTime.now());

        //这里 已经 通过AOP 反射 添加公共字段
        //设置创建人和修改人的ID
        /**
         * 在用户登录时创建token 就获取用户ID 再创建一个线程存放用户ID 之后再取出来
         */
//        employee.setCreateUser(BaseContext.getCurrentId());
//        employee.setUpdateUser(BaseContext.getCurrentId());

        return employeeMapper.AddUserMapper(employee);
    }

    /**
     * 分页查询员工
     * @param employeePageQueryDTO
     * @return
     */
    @Override
    public PageResult inquire(EmployeePageQueryDTO employeePageQueryDTO) {


        //开始分页查询
        //设置起点和终点
        PageHelper.startPage(employeePageQueryDTO.getPage(),employeePageQueryDTO.getPageSize());

        //调用SQL查询
        //Page插件 会把查询出来的结果 根据你设置的参数 帮你设置好 你再取出来返回即可
        Page<Employee> page=employeeMapper.PageQuery(employeePageQueryDTO);

        //返回查询结果的总页数 和 列表
        PageResult pageResult=new PageResult();
        pageResult.setTotal(page.getTotal());
        pageResult.setRecords(page.getResult());
        return pageResult;
    }

    /**
     * 根据ID查询员工信息
     * @param id
     * @return
     */
    @Override
    public Employee InquireUserID(Long id) {
        return employeeMapper.Inquire(id);
    }

    /**
     * 启用禁用账户状态功能
     * @param status
     * @param id
     * @return
     */
    @Override
    public int startORForb(Integer status, Long id) {
        Employee employee=Employee.builder()
                .status(status)
                .id(id)
                .build();

        return employeeMapper.Update(employee);
    }

    /**
     * 修改账户信息
     * @param employeeDTO
     * @return
     */
    @Override
    public int UpdateUser(EmployeeDTO employeeDTO) {

        Employee employee=new Employee();
        BeanUtils.copyProperties(employeeDTO,employee);

        //这里 已经 通过AOP 反射 添加公共字段
//        employee.setUpdateUser(BaseContext.getCurrentId());
//        employee.setUpdateTime(LocalDateTime.now());

        return employeeMapper.Update(employee);
    }

}
